package cn.itsource.system.service.impl;

import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.service.IMenuService;
import cn.itsource.basic.service.Impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mochen
 * @since 2023-04-01
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> queryTree() {
        //查到所有部门
        List<Menu> all = menuMapper.loadAll();

        //构建Map,将List-all转为Map-all
        Map<Long, Menu> map = new HashMap<>();
        for (Menu menu : all) {
            map.put(menu.getId(), menu);
        }

        //构建最终要返回的集合
        List<Menu> result = new ArrayList<>();

        for (Menu menu : all) {
            Long pid = menu.getParentId();
            if (pid == null) {
                result.add(menu);
            } else {
                //父部门id找父部门对象
                Menu parent = map.get(pid);
                //将自己加入父部门的children集合
                parent.getChildren().add(menu);//parent.getChildren()--List<Menu> children;
            }
        }
        return result;
    }
}
